<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head>
    <meta charset="utf-8">


    <link href="/assets/css/all.css" rel="stylesheet" type="text/css">
    <script async src="/assets/js/all.js"></script>


    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({tex2jax: {inlineMath: [['«', '»']]}});
      MathJax.Hub.config.tex2jax.skipTags = ["script", "noscript", "style", "textarea", "annotation", "annotation-xml"];

    </script>
    <script async src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-AMS_HTML'></script>
    <!-- Google Analytics -->
    <script>
        window.ga = window.ga || function () {
            (ga.q = ga.q || []).push(arguments)
        };
        ga.l = +new Date;
        ga('create', 'UA-58002512-1', 'auto');
        ga('set', 'anonymizeIp', true);
        ga('send', 'pageview');
    </script>
    <script async src='https://www.google-analytics.com/analytics.js'></script>
    <!-- End Google Analytics -->

    <title>Nim by Example - Objects</title>

    <meta content="nanoc 4.9.9" name="generator">
    <meta content="colorful" http-equiv="Default-Style">
    <meta content="width=device-width, initial-scale=1" name=viewport>
</head>
<body>

<div id="sidebar">
    <div class="abs-hamburger">
        <div class="nav-toggle" onclick="sidebarClick();"><span></span></div>
    </div>
    <nav>
        <ul>
            <li><a href="/getting_started/">Getting Started</a></li>
            <li><a href="/hello_world/">Hello World</a></li>
            <li><a href="/comments/">Comments</a></li>
            <li><a href="/variables/">Variables</a>
                <ul>
                    <li><a href="/variables/result/">Result</a></li>
                    <li><a href="/variables/type_casting_inference/">Type Casting and Inference</a></li>
                </ul>
            </li>
            <li><a href="/if_else_while/">If, Else, While</a></li>
            <li><a href="/case/">Case Statements</a></li>
            <li><a href="/for_iterators/">For Loops &amp; Iterators</a></li>
            <li><a href="/procs/">Procs</a></li>
            <li><a href="/procvars/">First Class Functions</a></li>
            <li><a href="/block/">Blocks</a></li>
            <li><a href="/primitives/">Primitive Types</a></li>
            <li><a href="/types/">Type Aliases</a></li>
            <li><a href="/types/objects/">Object Types</a></li>
            <li><a href="/types/enums/">Enum Types</a></li>
            <li><a href="/types/distinct/">Distinct Types</a></li>
            <li><a href="/strings/">Strings</a></li>
            <li><a href="/arrays/">Arrays</a></li>
            <li><a href="/seqs/">Seqs</a></li>
            <li><a href="/bitsets/">Bitsets</a></li>
            <li><a href="/files/">Files</a></li>
            <li><a href="/json/">JSON</a></li>
            <li><a href="/varargs/">Varargs</a></li>
            <li><a href="/oop/">Object Oriented Programming</a></li>
            <li><a href="/macros/">Macros</a></li>
        </ul>


    </nav>
</div>

<article>
    <h1 id="objects">Objects</h1>

    <p>In Nim, objects are like structs from C family languages and define a grouping of fields. They are by default
        traced by the garbage collector, so there is no need to explicitly free them when allocated.</p>

    <pre><code class="language-nimrod"><span class="k">type</span>
  <span class="n">Animal</span><span class="o">*</span> <span class="o">=</span> <span class="k">object</span>
    <span class="n">name</span><span class="o">*</span><span class="p">,</span> <span class="n">species</span><span
                class="o">*</span><span class="p">:</span> <span class="kt">string</span>
    <span class="n">age</span><span class="p">:</span> <span class="kt">int</span>

<span class="k">proc </span><span class="nf">sleep</span><span class="o">*</span><span class="p">(</span><span
                class="n">a</span><span class="p">:</span> <span class="kd">var</span> <span
                class="n">Animal</span><span class="p">)</span> <span class="o">=</span>
  <span class="n">a</span><span class="p">.</span><span class="n">age</span> <span class="o">+=</span> <span class="mi">1</span>

<span class="k">proc </span><span class="nf">dead</span><span class="o">*</span><span class="p">(</span><span class="n">a</span><span
                class="p">:</span> <span class="n">Animal</span><span class="p">):</span> <span
                class="kt">bool</span> <span class="o">=</span>
  <span class="n">result</span> <span class="o">=</span> <span class="n">a</span><span class="p">.</span><span
                class="n">age</span> <span class="o">&gt;</span> <span class="mi">20</span>

<span class="kd">var</span> <span class="n">carl</span><span class="p">:</span> <span class="n">Animal</span>
<span class="n">carl</span> <span class="o">=</span> <span class="n">Animal</span><span class="p">(</span><span
                class="n">name</span> <span class="p">:</span> <span class="s">"Carl"</span><span class="p">,</span>
              <span class="n">species</span> <span class="p">:</span> <span class="s">"L. glama"</span><span
                class="p">,</span>
              <span class="n">age</span> <span class="p">:</span> <span class="mi">12</span><span class="p">)</span>

<span class="k">let</span> <span class="n">joe</span> <span class="o">=</span> <span class="n">Animal</span><span
                class="p">(</span><span class="n">name</span> <span class="p">:</span> <span class="s">"Joe"</span><span
                class="p">,</span>
                 <span class="n">species</span> <span class="p">:</span> <span class="s">"H. sapiens"</span><span
                class="p">,</span>
                 <span class="n">age</span> <span class="p">:</span> <span class="mi">23</span><span class="p">)</span>

<span class="n">assert</span><span class="p">(</span><span class="ow">not</span> <span class="n">carl</span><span
                class="p">.</span><span class="n">dead</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="mf">0</span><span class="p">..</span><span
                class="mi">10</span><span class="p">:</span>
  <span class="n">carl</span><span class="p">.</span><span class="n">sleep</span><span class="p">()</span>
<span class="n">assert</span> <span class="n">carl</span><span class="p">.</span><span
                class="n">dead</span></code></pre>

    <p>Object types are declared in a type section, as usual. They can be exported, and individual fields can also be
        exported. Fields can be safely exported without violating encapsulation because call syntax is equivalent
        between them.</p>

    <p>Initially, <code>carl</code> is created on the stack and initialized to zeros (or <code>""</code> in case of
        fields of type <code>string</code>), so its value is <code>[name = "", species = "", age = 0]</code>. It is
        mutable, so that means that the contents of <code>carl</code> can be changed. This also means it can be passed
        to functions that require a variable parameter, like <code>sleep()</code>, which can modify its value.</p>

    <p><code>joe</code> is also created on the stack, but it’s contents are immutable and can not be changed. Attempting
        to do so, say through <code>joe.age = 57</code>, will fail with an error at compile time.</p>

    <pre><code class="language-nimrod"><span class="k">let</span> <span class="n">mittens</span><span class="p">:</span> <span
            class="k">ref</span> <span class="n">Animal</span> <span class="o">=</span> <span class="n">new</span><span
            class="p">(</span><span class="n">Animal</span><span class="p">)</span>

<span class="n">mittens</span><span class="p">.</span><span class="n">name</span> <span class="o">=</span> <span
                class="s">"Mittens"</span>
<span class="n">mittens</span><span class="p">.</span><span class="n">species</span> <span class="o">=</span> <span
                class="s">"P. leo"</span>
<span class="n">mittens</span><span class="p">.</span><span class="n">age</span> <span class="o">=</span> <span
                class="mi">6</span>

<span class="n">mittens</span><span class="p">.</span><span class="n">sleep</span><span class="p">()</span></code></pre>

    <p><code>mittens</code> is a reference to an object allocated on the heap. The value of <code>mittens</code> cannot
        be changed, so <code>mittens</code> can never point to anything else, but the value that <code>mittens</code> is
        pointing at can and is changed from the default initialization value of zeros. Its mutability also means that
        <code>mittens</code> can be passed to functions that require a variable parameter.</p>

    <p>You might ask whether there is a more concise way of initializing reference types, and there is if you give the
        reference type a name:</p>

    <pre><code class="language-nimrod"><span class="k">type</span>
  <span class="n">AnimalRef</span><span class="o">*</span> <span class="o">=</span> <span class="k">ref</span> <span
                class="n">Animal</span>

<span class="k">let</span> <span class="n">spot</span> <span class="o">=</span> <span class="n">AnimalRef</span><span
                class="p">(</span><span class="n">name</span><span class="p">:</span> <span class="s">"Spot"</span><span
                class="p">,</span>
                   <span class="n">species</span><span class="p">:</span> <span class="s">"C. lupus"</span><span
                class="p">,</span>
                   <span class="n">age</span><span class="p">:</span> <span class="mi">1</span><span class="p">)</span></code></pre>

    <p>In many cases it is only wanted to have the object be a reference type, which is possible by declaring it as a
        <code>ref object</code>.</p>

    <pre><code class="language-nimrod"><span class="k">type</span>
  <span class="n">Thing</span><span class="o">*</span> <span class="o">=</span> <span class="k">ref</span> <span
                class="k">object</span>
    <span class="n">positionX</span><span class="o">*</span><span class="p">,</span> <span
                class="n">positionY</span><span class="o">*</span><span class="p">:</span> <span
                class="kt">int</span></code></pre>

</article>

<div id=nextprev>
    <a class="text-icon disabled" href="https://please-enable-js/" id=arrow-prev>↽</a>
    <a class="text-icon disabled" href="https://please-enable-js/" id=arrow-next>⇁</a>
</div>

<footer>
    <li><a href="https://github.com/flaviut/nim-by-example">Contribute</a></li>
    <li
    ><a href="#" onclick="toggleDarkMode(); return false;">Toggle dark mode</a></li>

</footer>
</body>
</html>
